package com.example.zzx.dovebook.bookshare.booksharedetail

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.MenuItem
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.lifecycle.Observer
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeResult
import com.example.baselibrary.commonutil.FormatUtil
import com.example.baselibrary.commonutil.Logger
import com.example.baselibrary.image.GlideManager
import com.example.zzx.dovebook.R
import com.example.zzx.dovebook.base.BaseActivity
import com.example.zzx.dovebook.base.extensions.startUserDetailActivity
import com.example.zzx.dovebook.base.model.BookShare
import com.example.zzx.dovebook.bookshare.booksharehome.CommentDialog
import com.example.zzx.dovebook.bookshare.booksharehome.model.Comment
import com.example.zzx.dovebook.bookshare.booksharehome.model.CommentReply
import com.example.zzx.dovebook.booktrace.BookTraceActivity
import com.example.zzx.dovebook.login.LoginCheck
import com.example.zzx.dovebook.user.UserManager
import com.example.zzx.dovebook.utils.AnimationUtil
import com.example.zzx.dovebook.utils.LocationUtil
import com.example.zzx.heartanimation.LikeLayout
import kotlinx.android.synthetic.main.activity_book_share_detail.*

class BookShareDetailActivity : BaseActivity<BookShareDetailViewModel>() {

    private lateinit var bookShare: BookShare

    private lateinit var commentDialog: CommentDialog

    override fun getLayoutId(): Int = R.layout.activity_book_share_detail

    override fun createViewModel(): Class<BookShareDetailViewModel> = BookShareDetailViewModel::class.java

    override fun getStatusBarColor(): Int = STATUS_BAR_TRANSPARENT

    override fun createRepository(): Any = BookShareDetailRepository()

    override fun initIntent(savedInstanceState: Bundle?) {
        bookShare = intent.getSerializableExtra(getString(R.string.book_share_arg_name)) as BookShare
    }

    override fun initViews(savedInstanceState: Bundle?) {
        setupToolbar()

        commentDialog = CommentDialog(this)

        bindBookShareViews()
    }

    private fun setupToolbar() {
        setSupportActionBar(toolbar)
        supportActionBar?.apply {
            setDisplayHomeAsUpEnabled(true)
            title = bookShare.bookTitle
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }

    private fun bindBookShareViews() {
        bookShare.apply {
            userNameTv.text = "@$userName"
            sexIcon.setImageResource(
                if (TextUtils.equals("女", userSex)) {
                    R.drawable.ic_sex_woman_white_16dp
                } else {
                    R.drawable.ic_sex_man_white_16dp
                }
            )
            GlideManager.loadImage(this@BookShareDetailActivity, bookImagePath, bookImage)
            //头像
            if (TextUtils.isEmpty(userAvatarPath)) {
                GlideManager.loadImage(
                    this@BookShareDetailActivity,
                    R.drawable.default_avatar, userAvatarImage
                )
            } else {
                GlideManager.loadImage(
                    this@BookShareDetailActivity,
                    userAvatarPath, userAvatarImage
                )
            }
            userAvatarImage.setOnClickListener {
                startUserDetailActivity(userId, userName)
            }
            //获取地址位置并绑定
            if (isLocationAvailable()) {
                placeTv.visibility = VISIBLE
                LocationUtil.geocodeSearch(this@BookShareDetailActivity, latitude, longitude,
                    object : GeocodeSearch.OnGeocodeSearchListener {
                        override fun onRegeocodeSearched(result: RegeocodeResult, resultCode: Int) {
                            if (resultCode != 1000) {
                                Logger.e(
                                    TAG, "onRegeocodeSearched -> location($latitude, $longitude) " +
                                            "获取地址失败"
                                )
                                return
                            }
                            result.regeocodeAddress.apply {
                                placeTv.text = "$province $city"
                            }
                        }

                        override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {
                        }

                    })
            }
            descriptionTv.text = description
            bookNameTv.text = bookTitle
            bookStateTv.text = bookStatusTip
        }
        bindActionsView()
    }


    private fun bindActionsView() {
        bookShare.apply {
            //点赞
            likeLayout.apply {
                setText(FormatUtil.countFormat(likeCount))
                initState(
                    if (isHasLike) {
                        STATE_FINAL
                    } else {
                        STATE_INITIAL
                    }
                )
                setOnClickListener {
                    if (isHasLike) {
                        cancelBookShareLike(this, bookShareId)
                    } else {
                        bookShareLike(this, bookShareId)
                    }
                }
            }
            //评论
            commentLayout.apply {
                setText(FormatUtil.countFormat(commentCount))
                setOnClickListener {
                    commentDialog.show(bookShare)
                }
            }
            //图书传递路径
            traceLayout.setOnClickListener {
                startBookTraceActivity()
            }
            //关注
            followTv.apply {
                if (TextUtils.equals(userId, UserManager
                        .getInstance(this@BookShareDetailActivity).loginUserId ?: "") ||
                        isHasFollowed) {
                    visibility = GONE
                } else {
                    visibility = VISIBLE
                    setOnClickListener {
                        follow(it)
                    }
                }
            }
        }
    }

    @LoginCheck
    private fun follow(view: View) {
        viewModel.follow(UserManager.getInstance(this).loginUserId, bookShare.uploadUserId)
            .observe(this, Observer {
                AnimationUtil.hide(view)
            })
    }

    /**
     * 跳转到[BookTraceActivity], 需要传递参数[bookShare.bookId]和[bookShare.bookStatus]
     */
    private fun startBookTraceActivity() {
        bookShare?.apply {
            val intent = Intent(this@BookShareDetailActivity, BookTraceActivity::class.java)
            intent.putExtra(getString(R.string.book_id_arg_name), bookId)
            intent.putExtra(getString(R.string.book_status_arg_name), bookStatus)
            startActivity(intent)
        }
    }

    /**
     * 点赞
     */
    @LoginCheck
    private fun bookShareLike(targetView: LikeLayout, bookShareId: String) {
        viewModel.bookShareLike(bookShareId, UserManager.getInstance(this).loginUserId ?: "")
            .observe(this, Observer { success ->
                bookShare?.apply {
                    if (success) {
                        isHasLike = true
                        likeCount++
                        targetView.toggle(FormatUtil.countFormat(likeCount))
                    }
                }
            })
    }

    @LoginCheck
    private fun cancelBookShareLike(targetView: LikeLayout, bookShareId: String) {
        viewModel.cancelBookShareLike(bookShareId, UserManager.getInstance(this).loginUserId ?: "")
            .observe(this, Observer { success ->
                bookShare?.apply {
                    if (success) {
                        isHasLike = false
                        likeCount--
                        targetView.toggle(FormatUtil.countFormat(likeCount))
                    }
                }
            })
    }

    private fun isLocationAvailable(): Boolean {
        return !(bookShare?.latitude == 0.0 && bookShare?.longitude == 0.0)
    }

    /**
     * 展示评论
     */
    fun showReplyEdit(comment: Comment) {
        commentDialog.showReplyEdit(comment)
    }

    /**
     * 展示回复评论的回复
     */
    fun showReplyEdit(reply: CommentReply, replyParentComment: Comment) {
        commentDialog.showReplyEdit(reply, replyParentComment)
    }
}